package ar.unrn.tp1.persistence.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.joda.time.DateTime;
import org.springframework.transaction.annotation.Transactional;

import ar.unrn.tp1.model.Articulo;
import ar.unrn.tp1.model.Autor;
import ar.unrn.tp1.model.Hemeroteca;
import ar.unrn.tp1.model.Revista;

public class HibernateHemeroteca extends HibernatePersistentObject<Revista>
		implements Hemeroteca {

	@Override
	@Transactional
	public void nuevaRevista(Revista revista) {
		store(revista);
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Articulo> articulosPorRevista(DateTime date) {
		Query hqlQuery = getSession()
				.createQuery(
						"select a from Revista r join r.articulos a where r.edicion = :edicion")
				.setDate("edicion", date.toDate());
		return hqlQuery.list();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Autor> autoresPorArticulo(String nombreArticulo) {
		Query hqlQuery = getSession()
				.createQuery(
						"select aut from Articulo art join art.autores aut where art.nombre = :nombreArticulo")
				.setString("nombreArticulo", nombreArticulo);
		return hqlQuery.list();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Articulo> articulosPorTema(String tema) {
		Query hqlQuery = getSession()
				.createQuery(
						"select art from Revista r join r.articulos art where :tema in elements(art.temas) and r.edicion >= '2014-01-01 00:00:00'")
				.setString("tema", tema);
		return hqlQuery.list();
	}

	@Transactional(readOnly = true)
	public Revista revistaMasViejaPorTema(String tema) {
		Query hqlQuery = getSession()
				.createQuery(
						"select r from Revista r where :tema in elements(r.articulos.temas) and r.edicion in (select min(r.edicion) from Revista r)")
				.setString("tema", tema);
		return (Revista) hqlQuery.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Object[]> revistasConMasDe2Articulos() {
		Query hqlQuery = getSession()
				.createQuery(
						"select r.edicion, count(r) from Revista r join r.articulos group by r.edicion having count(r) > 2");
		return hqlQuery.list();
	}

	@Override
	@Transactional(readOnly = true)
	public Revista recuperarRevista(DateTime edicion) {
		Query hqlQuery = getSession()
				.createQuery(
						"from Revista r where r.edicion = :edicion")
				.setDate("edicion", edicion.toDate());
		return (Revista)hqlQuery.uniqueResult();
	}
}
